package com.linkin.homepage.base.net;


import android.text.TextUtils;

import com.google.gson.Gson;
import com.linkin.homepage.BuildConfig;
import com.linkin.homepage.base.util.Predictor;
import com.linkin.homepage.util.JsonUtils;


public class ResponseData<T> implements IResponseData {

    public String msg = "";
    public int errno = ERROR_PARSE_JSON;
    public int success = ERROR_TIME_OUT;
    public T data = null;

    @Override
    public void setErrorCode(int errorCode) {
        this.errno = errorCode;
    }

    @Override
    public int getErrorCode() {
        return errno;
    }

    @Override
    public int getSuccessResponse() {
        return success;
    }

    @Override
    public void setMsg(String msg) {
        this.msg = msg;
    }

    @Override
    public boolean hasData() {
        return Predictor.isNotEmpty(data);
    }

    public static ResponseData fromJson(Gson gson, String json, Class clazz) {
        if (TextUtils.isEmpty(json)) {
            ResponseData response = new ResponseData();
            response.setMsg("数据异常");
            return response;
        }

        ResponseData response;
        try {
            response = (ResponseData) JsonUtils.fromJson(gson, json, ResponseData.class, clazz);
            if (response == null) {
                response = new ResponseData();
                response.setMsg("数据异常");
            }
        } catch (Exception e) {
            // for test
            if (BuildConfig.DEBUG) {
                if (clazz != null) {
                    JsonUtils.e("class:" + clazz.toString() + "\nerror:" + e.getMessage() + "\nstr:" + json);
                } else {
                    JsonUtils.e("error:" + e.getMessage() + "\nstr:" + json);
                }
            }

            response = new ResponseData();
            response.setMsg("数据异常");
        }
        return response;
    }
}
